package pers.jason.wppm.security.core.social;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.crypto.encrypt.Encryptors;
import org.springframework.social.config.annotation.EnableSocial;
import org.springframework.social.config.annotation.SocialConfigurerAdapter;
import org.springframework.social.connect.ConnectionFactoryLocator;
import org.springframework.social.connect.ConnectionSignUp;
import org.springframework.social.connect.UsersConnectionRepository;
import org.springframework.social.connect.jdbc.JdbcUsersConnectionRepository;
import org.springframework.social.connect.web.ProviderSignInUtils;
import org.springframework.social.security.SpringSocialConfigurer;
import pers.jason.wppm.security.core.properties.SecurityProperties;

import javax.sql.DataSource;

/**
 * @ClassName: SocialConfig
 * @Author: JZH
 * @Date: 2018/11/25 1:24
 */
@Order(1)
@EnableSocial
@Configuration
public class SocialConfig extends SocialConfigurerAdapter {

    @Autowired
    private DataSource dataSource;

    @Autowired
    private SecurityProperties securityProperties;

    @Autowired
    private ConnectionFactoryLocator connectionFactoryLocator;

    @Autowired(required = false)
    private ConnectionSignUp connectionSignUp;

    @Override
    public UsersConnectionRepository getUsersConnectionRepository(ConnectionFactoryLocator connectionFactoryLocator) {
        /**
         * textEncryptor：加解密
         */
        JdbcUsersConnectionRepository jdbcUsersConnectionRepository = new JdbcUsersConnectionRepository(dataSource, connectionFactoryLocator, Encryptors.noOpText());
        //jdbcUsersConnectionRepository.setTablePrefix("wppm_"); //表明只能是userconnection，但是可以加前缀
        if(null != connectionSignUp) { //connectionSignUp接口用来免注册，如果客户端实现了，那么就让客户端自己后台注册即可
            jdbcUsersConnectionRepository.setConnectionSignUp(connectionSignUp);
        }
        return jdbcUsersConnectionRepository;
    }

    @Bean
    public SpringSocialConfigurer springSocialConfigurer() {
        SpringSocialConfigurer springSocialConfigurer = new DefaultSpringSocialConfig(securityProperties.getSocial().getFilterProcessesUrl());
        springSocialConfigurer.signupUrl(securityProperties.getBrowser().getSignUpUrl());
        return springSocialConfigurer;
    }

    /**
     * 工具类：
     * 1. 注册过程中获取spring social的信息
     * 2. 注册完成后将业务系统的用户id返回给spring social
     */
    @Bean
    public ProviderSignInUtils providerSignInUtils() {
        return new ProviderSignInUtils(connectionFactoryLocator, getUsersConnectionRepository(connectionFactoryLocator));
    }

}
